<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .bg-container {
      width: 600px;
      height: 400px;
      margin: 100px auto;
    }

    .bg-container #bg-image {
      width: 100%;
      height: 100%;
    }
  </style>
</head>

<body>
<div id="background">
  <button data-src="/images/bg1.jpg">背景1</button>
  <button data-src="/images/bg2.jpg">背景2</button>
</div>
<div class="bg-container">
  <img id="bg-image" src="/images/bg1.jpg" />
</div>
<script>
  class BackgroundImage {
    constructor() {
      this.bgImage = document.querySelector('#bg-image');
    }
    setSrc(src) {
      this.bgImage.src = src;
    }
  }
  class LoadingBackgroundImage {
    static LOADING_URL= `/images/loading.gif`;
    constructor() {
      this.backgroundImage = new BackgroundImage();
    }
    setSrc(src) {
      this.backgroundImage.setSrc(LoadingBackgroundImage.LOADING_URL);
      let img = new Image();
      img.onload = () => {
        this.backgroundImage.setSrc(src);
      }
      img.src = src;
    }
  }

  let container = document.querySelector('#background');

  let loadingBackgroundImage = new LoadingBackgroundImage();
  container.addEventListener('click', function (event) {
    let src = event.target.dataset.src;
    loadingBackgroundImage.setSrc(src + '?ts=' + Date.now());
  });
</script>
</body>

</html>
